'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/lib/auth-client';
import { QUESTION_BANK, TOPIC_ID_TO_NAME } from '@questions';
import {
  ArrowLeft,
  Clock,
  CheckCircle,
  XCircle,
  Lightbulb,
  Target,
  Trophy
} from 'lucide-react';

interface Question {
  stem: string;
  difficulty: number;
  answer: (string | number)[];
  hint1?: string;
  hint2?: string;
  solution: string;
}

interface PracticeSession {
  sessionId: number | null;
  topicId: string;
  topicName: string;
  questions: Question[];
  currentIndex: number;
  answers: (string | null)[];
  correctAnswers: boolean[];
  showHint: boolean[];
  completed: boolean;
  score: number;
  startTime: Date;
  questionStartTime: Date;
}

export default function PracticeSessionPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, loading: authLoading } = useAuth();

  const [session, setSession] = useState<PracticeSession | null>(null);
  const [userAnswer, setUserAnswer] = useState<string>('');
  const [showExplanation, setShowExplanation] = useState(false);
  const [showResult, setShowResult] = useState(false);
  const [loading, setLoading] = useState(true);
  const [timeRemaining, setTimeRemaining] = useState<number | null>(null);
  const [showSolution, setShowSolution] = useState(false); // 显示完整解题思路

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/auth/login');
      } else {
        initializePractice();
      }
    }
  }, [authLoading, user]);

  // 计时器
  useEffect(() => {
    if (!session || session.completed) return;

    const timer = setInterval(() => {
      const elapsed = Math.floor((Date.now() - session.startTime.getTime()) / 1000);
      const remaining = Math.max(0, 1800 - elapsed); // 30分钟 = 1800秒
      setTimeRemaining(remaining);

      if (remaining === 0) {
        handleTimeUp();
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [session]);

  async function initializePractice() {
    try {
      // 获取练习参数
      const topicId = searchParams.get('topicId') || '';
      const topicName = searchParams.get('topicName') || '';
      const topicsParam = searchParams.get('topics') || ''; // 多个知识点
      const count = parseInt(searchParams.get('count') || '10');
      const difficultyParam = searchParams.get('difficulty') || '1,2,3,4,5';
      const selectedDifficulties = difficultyParam.split(',').map(d => parseInt(d));

      // 获取用户已答对的题目列表
      let correctAnswers: { topic_id: string; question_index: number }[] = [];
      try {
        const token = localStorage.getItem('auth_token');
        const response = await fetch('/api/practice/correct-answers', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        if (response.ok) {
          const data = await response.json();
          correctAnswers = data.correctAnswers || [];
        }
      } catch (err) {
        console.warn('获取已答对题目失败:', err);
        // 继续执行，不阻断练习
      }

      // 获取未复习的错题索引（这些题目也要从练习中排除）
      let unreviewedMistakes: { topic_id: string; question_index: number }[] = [];
      try {
        const token = localStorage.getItem('auth_token');
        const response = await fetch('/api/mistakes/unreviewed-indices', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        if (response.ok) {
          const data = await response.json();
          unreviewedMistakes = data.unreviewedMistakes || [];
        }
      } catch (err) {
        console.warn('获取未复习错题失败:', err);
        // 继续执行，不阻断练习
      }

      // 支持单个知识点或多个知识点
      let questions: Question[] = [];
      let finalTopicId = topicId;
      let finalTopicName = topicName;

      if (topicsParam) {
        // 多个知识点混合练习
        const topicIds = topicsParam.split(',');
        questions = generateMultiTopicQuestions(topicIds, count, selectedDifficulties, correctAnswers, unreviewedMistakes);
        finalTopicId = 'mixed';
        finalTopicName = '混合练习';
      } else if (topicId) {
        // 单个知识点练习
        questions = generateQuestions(topicId, count, selectedDifficulties, correctAnswers, unreviewedMistakes);
        finalTopicId = topicId;
        finalTopicName = topicName;
      } else {
        router.push('/practice/free');
        return;
      }

      // 生成练习题目（按难度筛选）
      // questions 已经在上面生成了

      if (questions.length === 0) {
        alert('所选知识点和难度没有可用题目，或所有题目已答对');
        router.push('/practice/free');
        return;
      }

      // 调用API创建练习会话
      const token = localStorage.getItem('auth_token');
      const response = await fetch('/api/practice/start', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          topicId: finalTopicId,
          topicName: finalTopicName,
          questionCount: questions.length,
          difficultyRange: '1-5',
        }),
      });

      const data = await response.json();
      let sessionId = null;

      if (data.success) {
        sessionId = data.data.sessionId;
      } else {
        console.error('创建会话失败:', data);
      }

      const newSession: PracticeSession = {
        sessionId,
        topicId: finalTopicId,
        topicName: finalTopicName,
        questions,
        currentIndex: 0,
        answers: new Array(questions.length).fill(null),
        correctAnswers: new Array(questions.length).fill(false),
        showHint: new Array(questions.length).fill(false),
        completed: false,
        score: 0,
        startTime: new Date(),
        questionStartTime: new Date(),
      };

      setSession(newSession);
      setLoading(false);
    } catch (error) {
      console.error('初始化练习失败:', error);
    } finally {
      setLoading(false);
    }
  }

  // 生成多知识点混合题目
  function generateMultiTopicQuestions(
    topicIds: string[], 
    count: number, 
    selectedDifficulties: number[] = [1,2,3,4,5],
    correctAnswers: { topic_id: string; question_index: number }[] = [],
    unreviewedMistakes: { topic_id: string; question_index: number }[] = []
  ): Question[] {
    let allQuestions: Question[] = [];
    
    // 从每个知识点收集题目
    topicIds.forEach(topicId => {
      const topicName = TOPIC_ID_TO_NAME[topicId] || topicId;
      const topicQuestions = QUESTION_BANK[topicName] || [];
      
      // 获取该知识点已答对的题目索引
      const correctIndices = correctAnswers
        .filter(ca => ca.topic_id === topicId)
        .map(ca => ca.question_index);
      
      // 获取该知识点未复习的错题索引
      const unreviewedIndices = unreviewedMistakes
        .filter(um => um.topic_id === topicId)
        .map(um => um.question_index);
      
      // 按难度过滤，并排除已答对的题目和未复习的错题
      const filteredQuestions = topicQuestions.filter((q, index) => 
        selectedDifficulties.includes(q.difficulty) && 
        !correctIndices.includes(index) &&
        !unreviewedIndices.includes(index)
      );
      
      allQuestions = allQuestions.concat(filteredQuestions);
    });

    // 随机打乱并选择指定数量
    const shuffled = [...allQuestions].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, Math.min(count, shuffled.length));
  }

  function generateQuestions(
    topicId: string, 
    count: number, 
    selectedDifficulties: number[] = [1,2,3,4,5],
    correctAnswers: { topic_id: string; question_index: number }[] = [],
    unreviewedMistakes: { topic_id: string; question_index: number }[] = []
  ): Question[] {
    // 将英文ID转换为中文名称
    const topicName = TOPIC_ID_TO_NAME[topicId] || topicId;
    const topicQuestions = QUESTION_BANK[topicName] || [];

    if (topicQuestions.length === 0) {
      console.error(`未找到题目: topicId=${topicId}, topicName=${topicName}`);
      return [];
    }

    // 获取该知识点已答对的题目索引
    const correctIndices = correctAnswers
      .filter(ca => ca.topic_id === topicId)
      .map(ca => ca.question_index);

    // 获取该知识点未复习的错题索引
    const unreviewedIndices = unreviewedMistakes
      .filter(um => um.topic_id === topicId)
      .map(um => um.question_index);

    // 根据难度过滤题目，并排除已答对的题目和未复习的错题
    const filteredQuestions = topicQuestions.filter((q, index) => 
      selectedDifficulties.includes(q.difficulty) && 
      !correctIndices.includes(index) &&
      !unreviewedIndices.includes(index)
    );

    if (filteredQuestions.length === 0) {
      console.warn(`没有符合选择难度的题目或所有题目已答对/在错题本中: topicName=${topicName}, difficulties=${selectedDifficulties.join(',')}`);
      return [];
    }

    // 随机选择题目
    const shuffled = [...filteredQuestions].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, Math.min(count, shuffled.length));
  }

  function handleTimeUp() {
    if (!session) return;
    alert('时间到！练习已结束');
    finishPractice();
  }

  // 处理"不会做"
  async function handleDontKnow() {
    if (!session) return;

    const currentQuestion = session.questions[session.currentIndex];
    const correctAnswer = currentQuestion.answer;

    // 计算时间
    const timeSpent = Math.floor((new Date().getTime() - session.questionStartTime.getTime()) / 1000);

    // 更新本地状态：标记为错误
    const newAnswers = [...session.answers];
    newAnswers[session.currentIndex] = '不会做';

    const newCorrectAnswers = [...session.correctAnswers];
    newCorrectAnswers[session.currentIndex] = false; // 不会做视为答错

    setSession({
      ...session,
      answers: newAnswers,
      correctAnswers: newCorrectAnswers,
    });

    // 提交到后端，标记为错误，加入错题本
    try {
      const token = localStorage.getItem('auth_token');
      await fetch('/api/practice/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          sessionId: session.sessionId,
          topicId: session.topicId,
          topicName: session.topicName,
          questionIndex: session.currentIndex,
          questionStem: currentQuestion.stem,
          userAnswer: '不会做',
          correctAnswer: correctAnswer,
          isCorrect: false, // 标记为错误
          timeSpent,
          hintsUsed: 0,
          difficulty: currentQuestion.difficulty || 1,
          solution: currentQuestion.solution || '',
        }),
      });
    } catch (error) {
      console.error('提交"不会做"记录失败:', error);
    }

    // 显示解题思路
    setShowSolution(true);
    setShowExplanation(true);
  }

  // 智能答案匹配函数
  function checkAnswer(userAnswer: string, correctAnswers: any[]): boolean {
    const userInput = userAnswer.trim().toLowerCase();

    // 遍历所有可能的正确答案
    for (const correctAns of correctAnswers) {
      const correctStr = correctAns.toString().toLowerCase();

      // 1. 完全匹配
      if (userInput === correctStr) {
        return true;
      }

      // 2. 提取用户输入中的所有数字
      const userNumbers = userInput.match(/\d+\.?\d*/g) || [];
      const correctNumbers = correctStr.match(/\d+\.?\d*/g) || [];

      // 如果数字数量相同
      if (userNumbers.length === correctNumbers.length && userNumbers.length > 0) {
        // 检查是否包含所有正确数字（顺序可以不同）
        const sortedUser = [...userNumbers].sort();
        const sortedCorrect = [...correctNumbers].sort();

        if (JSON.stringify(sortedUser) === JSON.stringify(sortedCorrect)) {
          return true;
        }
      }

      // 3. 单个数字匹配（如果只有一个答案）
      if (userNumbers.length === 1 && correctNumbers.length === 1) {
        if (userNumbers[0] === correctNumbers[0]) {
          return true;
        }
      }
    }

    return false;
  }

  async function handleAnswerSubmit() {
    if (!session || !userAnswer.trim()) return;

    const currentQuestion = session.questions[session.currentIndex];
    const correctAnswer = currentQuestion.answer;

    // 使用智能答案匹配
    const isCorrect = checkAnswer(userAnswer, correctAnswer);

    // 计算答题时间
    const timeSpent = Math.floor((new Date().getTime() - session.questionStartTime.getTime()) / 1000);

    // 更新本地状态
    const newAnswers = [...session.answers];
    newAnswers[session.currentIndex] = userAnswer;

    const newCorrectAnswers = [...session.correctAnswers];
    newCorrectAnswers[session.currentIndex] = isCorrect;

    setSession({
      ...session,
      answers: newAnswers,
      correctAnswers: newCorrectAnswers,
    });

    // 提交答案到API
    if (session.sessionId) {
      const token = localStorage.getItem('auth_token');
      try {
        const response = await fetch('/api/practice/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
          },
          body: JSON.stringify({
            sessionId: session.sessionId,
            topicId: session.topicId,
            topicName: session.topicName,
            questionIndex: session.currentIndex,
            questionStem: currentQuestion.stem,
            userAnswer,
            correctAnswer: correctAnswer,
            isCorrect,
            timeSpent,
            hintsUsed: 0,
            difficulty: currentQuestion.difficulty || 1,
            solution: currentQuestion.solution || '',
          }),
        });

        if (!response.ok) {
          console.error('提交答案失败:', await response.text());
        }
      } catch (error) {
        console.error('提交答案错误:', error);
      }
    }

    setShowExplanation(true);
  }

  function handleNextQuestion() {
    if (!session) return;

    if (session.currentIndex < session.questions.length - 1) {
      // 下一题
      setSession({
        ...session,
        currentIndex: session.currentIndex + 1,
        questionStartTime: new Date(),
      });
      setUserAnswer('');
      setShowExplanation(false);
      setShowSolution(false);
    } else {
      // 完成练习
      finishPractice();
    }
  }

  async function finishPractice() {
    if (!session) return;

    // 计算得分
    const correctCount = session.correctAnswers.filter(Boolean).length;
    const score = Math.round((correctCount / session.questions.length) * 100);
    const totalTime = Math.floor((new Date().getTime() - session.startTime.getTime()) / 1000);

    // 调用API完成练习
    if (session.sessionId) {
      const token = localStorage.getItem('auth_token');
      await fetch('/api/practice/complete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          sessionId: session.sessionId,
          correctCount,
          totalTime,
          score,
        }),
      });
    }

    setSession({
      ...session,
      completed: true,
      score,
    });
    setShowResult(true);
  }

  function toggleHint() {
    if (!session) return;
    
    const newShowHint = [...session.showHint];
    newShowHint[session.currentIndex] = !newShowHint[session.currentIndex];
    
    setSession({
      ...session,
      showHint: newShowHint
    });
  }

  function formatTime(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div>
          <p className="text-gray-600">正在准备练习题目...</p>
        </div>
      </div>
    );
  }

  if (!session) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-gray-600">练习初始化失败，请重试</p>
          <button
            onClick={() => router.back()}
            className="mt-4 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  if (showResult) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
        <div className="max-w-4xl mx-auto px-4 py-8">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="glassmorphism p-8 rounded-2xl text-center"
          >
            <Trophy className="w-16 h-16 text-yellow-500 mx-auto mb-4" />
            <h1 className="text-3xl font-bold text-gray-800 mb-2">练习完成！</h1>
            <p className="text-xl text-gray-600 mb-6">你的得分：{session.score}%</p>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
              <div className="glassmorphism p-4 rounded-xl">
                <div className="text-2xl font-bold text-indigo-600">{session.questions.length}</div>
                <div className="text-sm text-gray-600">总题数</div>
              </div>
              <div className="glassmorphism p-4 rounded-xl">
                <div className="text-2xl font-bold text-green-600">
                  {Math.round(session.score * session.questions.length / 100)}
                </div>
                <div className="text-sm text-gray-600">正确数</div>
              </div>
              <div className="glassmorphism p-4 rounded-xl">
                <div className="text-2xl font-bold text-purple-600">
                  {formatTime(Math.floor((new Date().getTime() - session.startTime.getTime()) / 1000))}
                </div>
                <div className="text-sm text-gray-600">用时</div>
              </div>
            </div>
            
            <div className="flex justify-center space-x-4">
              <button
                onClick={() => router.push('/dashboard')}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium"
              >
                返回首页
              </button>
              <button
                onClick={() => router.push('/practice/free')}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium"
              >
                继续练习
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  const currentQuestion = session.questions[session.currentIndex];
  const progress = ((session.currentIndex + 1) / session.questions.length) * 100;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => router.push('/dashboard')}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                title="返回学习仪表盘"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <div className="flex items-center space-x-2">
                <Target className="w-6 h-6 text-indigo-500" />
                <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                  练习模式
                </h1>
              </div>
            </div>
            
            <div className="flex items-center space-x-4">
              {timeRemaining !== null && (
                <div className="flex items-center space-x-2 px-3 py-1 bg-white/20 rounded-lg">
                  <Clock className="w-4 h-4 text-gray-600" />
                  <span className="font-mono text-sm">{formatTime(timeRemaining)}</span>
                </div>
              )}
              <div className="text-sm text-gray-600">
                {session.currentIndex + 1} / {session.questions.length}
              </div>
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-4xl mx-auto px-4 py-8">
        {/* 进度条 */}
        <div className="mb-8">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm font-medium text-gray-600">练习进度</span>
            <span className="text-sm font-medium text-gray-600">{Math.round(progress)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <motion.div
              className="bg-gradient-to-r from-indigo-500 to-purple-600 h-2 rounded-full"
              initial={{ width: 0 }}
              animate={{ width: `${progress}%` }}
              transition={{ duration: 0.5 }}
            />
          </div>
        </div>

        {/* 题目卡片 */}
        <motion.div
          key={session.currentIndex}
          initial={{ opacity: 0, x: 50 }}
          animate={{ opacity: 1, x: 0 }}
          className="glassmorphism p-8 rounded-2xl mb-8"
        >
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center space-x-2">
              <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
                难度 {currentQuestion.difficulty}
              </span>
            </div>
            <button
              onClick={toggleHint}
              className="p-2 rounded-lg hover:bg-white/20 transition-colors"
              title="提示"
            >
              <Lightbulb className={`w-5 h-5 ${session.showHint[session.currentIndex] ? 'text-yellow-500' : 'text-gray-400'}`} />
            </button>
          </div>

          <div className="mb-6">
            <h2 className="text-xl font-semibold text-gray-800 mb-4">
              {currentQuestion.stem}
            </h2>
            
            {session.showHint[session.currentIndex] && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                className="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4 rounded-r-lg"
              >
                <div className="flex items-start">
                  <Lightbulb className="w-5 h-5 text-yellow-500 mr-2 mt-0.5" />
                  <div>
                    <p className="text-sm text-yellow-800 font-medium">提示1：</p>
                    <p className="text-sm text-yellow-700">{currentQuestion.hint1}</p>
                    {currentQuestion.hint2 && (
                      <>
                        <p className="text-sm text-yellow-800 font-medium mt-2">提示2：</p>
                        <p className="text-sm text-yellow-700">{currentQuestion.hint2}</p>
                      </>
                    )}
                  </div>
                </div>
              </motion.div>
            )}
          </div>

          {/* 答案输入 */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              请输入答案：
            </label>
            <div className="mb-2 text-xs text-gray-500 bg-blue-50 p-2 rounded border border-blue-200">
              <span className="font-medium">💡 答题提示：</span>
              <span className="ml-1">
                如果题目问&ldquo;鸡兔各多少只&rdquo;，可以输入&ldquo;30 10&rdquo;或&ldquo;10 30&rdquo;或&ldquo;30&rdquo;或&ldquo;10&rdquo;，系统会智能识别。
                支持多种格式：数字、带单位的答案等。
              </span>
            </div>
            <input
              type="text"
              value={userAnswer}
              onChange={(e) => setUserAnswer(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter' && !showExplanation) {
                  handleAnswerSubmit();
                }
              }}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              placeholder="请输入你的答案..."
              disabled={showExplanation}
            />
          </div>

          {/* 解析 */}
          {showExplanation && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="mb-6"
            >
              <div className={`p-4 rounded-lg border-l-4 ${
                session.correctAnswers[session.currentIndex]
                  ? 'bg-green-50 border-green-400'
                  : 'bg-red-50 border-red-400'
              }`}>
                <div className="flex items-start mb-2">
                  {session.correctAnswers[session.currentIndex] ? (
                    <CheckCircle className="w-5 h-5 text-green-500 mr-2 mt-0.5" />
                  ) : (
                    <XCircle className="w-5 h-5 text-red-500 mr-2 mt-0.5" />
                  )}
                  <div>
                    <p className={`font-medium ${
                      session.correctAnswers[session.currentIndex]
                        ? 'text-green-800'
                        : 'text-red-800'
                    }`}>
                      {session.correctAnswers[session.currentIndex] ? '回答正确！' : '回答错误'}
                    </p>
                    <p className={`text-sm ${
                      session.correctAnswers[session.currentIndex]
                        ? 'text-green-700'
                        : 'text-red-700'
                    }`}>
                      正确答案：{currentQuestion.answer.join(' 或 ')}
                    </p>
                  </div>
                </div>
                <div className="mt-3 p-3 bg-white/50 rounded-lg">
                  <p className="text-sm font-medium text-gray-800 mb-1">详细解析：</p>
                  <div className="text-sm text-gray-700 whitespace-pre-line">
                    {currentQuestion.solution}
                  </div>
                </div>
              </div>
            </motion.div>
          )}

          {/* 不会做 - 显示完整解题思路 */}
          {showSolution && !showExplanation && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="mb-6 p-4 bg-indigo-50 border-l-4 border-indigo-400 rounded-r-lg"
            >
              <p className="text-sm font-medium text-indigo-800 mb-2">📖 完整解题思路：</p>
              <div className="text-sm text-indigo-700 whitespace-pre-line">
                {currentQuestion.solution}
              </div>
              <p className="text-xs text-indigo-600 mt-3">
                💡 看完解题思路后，可以尝试自己做一遍，或者直接查看答案。
              </p>
            </motion.div>
          )}

          {/* 操作按钮 */}
          <div className="flex justify-between">
            {!showExplanation ? (
              <button
                onClick={handleDontKnow}
                className="px-6 py-3 rounded-lg font-medium bg-gray-100 hover:bg-gray-200 text-gray-700 transition-all"
              >
                🤔 不会做
              </button>
            ) : (
              <div></div>
            )}
            {!showExplanation ? (
              <button
                onClick={handleAnswerSubmit}
                disabled={!userAnswer.trim()}
                className={`px-6 py-3 rounded-lg font-medium transition-all ${
                  userAnswer.trim()
                    ? 'glassmorphism-button hover:scale-105'
                    : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                }`}
              >
                提交答案
              </button>
            ) : (
              <button
                onClick={handleNextQuestion}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium hover:scale-105 transition-transform"
              >
                {session.currentIndex < session.questions.length - 1 ? '下一题' : '完成练习'}
              </button>
            )}
          </div>
        </motion.div>
      </div>
    </div>
  );
}
